package com.msxt.utils;

import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 百度地图API工具类
 */
public class BaiduUtil {

    private static final Logger logger = LoggerFactory.getLogger(BaiduUtil.class);

    /**
     * 根据经纬度获得省市区信息
     * @param key 百度API密钥
     * @param lng 经度
     * @param lat 纬度
     * @return 包含省市区信息的Map
     */
//    public static Map<String, String> getCityByLonLat(String key, String lng, String lat) {
//        String location = lat + "," + lng;
//        try {
//            String url = "http://api.map.baidu.com/reverse_geocoding/v3/?ak=" + key
//                    + "&output=json&coordtype=wgs84ll&location=" + location;
//            String result = HttpClientUtils.doGet(url);
//
//            JSONObject response = JSONObject.parseObject(result);
//            JSONObject addressComponent = response.getJSONObject("result")
//                    .getJSONObject("addressComponent");
//
//            Map<String, String> area = new HashMap<>();
//            area.put("province", addressComponent.getString("province"));
//            area.put("city", addressComponent.getString("city"));
//            area.put("district", addressComponent.getString("district"));
//            area.put("street", addressComponent.getString("street"));
//            return area;
//        } catch (Exception e) {
//            logger.error("获取地理位置信息失败", e);
//            return null;
//        }
//    }

    /**
     * 获取API访问token
     * @param ak 百度云API Key
     * @param sk 百度云Secret Key
     * @return access_token
     */
    public static String getAuth(String ak, String sk) {
        String authHost = "https://aip.baidubce.com/oauth/2.0/token?";
        String getAccessTokenUrl = authHost
                + "grant_type=client_credentials"
                + "&client_id=" + ak
                + "&client_secret=" + sk;

        try {
            URL realUrl = new URL(getAccessTokenUrl);
            HttpURLConnection connection = (HttpURLConnection) realUrl.openConnection();
            connection.setRequestMethod("GET");
            connection.connect();

            StringBuilder result = new StringBuilder();
            try (BufferedReader in = new BufferedReader(
                    new InputStreamReader(connection.getInputStream()))) {
                String line;
                while ((line = in.readLine()) != null) {
                    result.append(line);
                }
            }

            JSONObject jsonObject = JSONObject.parseObject(result.toString());
            return jsonObject.getString("access_token");
        } catch (Exception e) {
            logger.error("获取百度API token失败", e);
            return null;
        }
    }
}